/*
 *	fftrun.c
 *
 *	fftrun.lib
 */

#include <string.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include "fft.h"
#include "fftrun.h"

//
// Input:   bufIn[N]
// Output:  bufProc[N*M]
// Temp:    buff[N*M]
// Input:   win[N*M]
// Input:   N - input size
// Input:   M - overlapped coefficient
//
void forwardFFTRun(const __int16* bufIn, float* bufProc, float* buff, const float* win, const int N, const int M)
{
	int i, j;
	if((NULL == buff) || (NULL == bufIn) || (NULL == bufProc))
	{
		return;
	}

	// overlap
	for(i = 0; i < N; ++i)
	{
		for(j = 0; j < M-1; ++j)
		{
			buff[i+j*N] = buff[i+(j+1)*N];
		}
		buff[i+(M-1)*N] = bufIn[i] / 32767.0f;
	}

    if(win) // windowing
    {
        for(i = 0; i < N*M; ++i)
        {
            bufProc[i] = buff[i] * win[i];
        }
    }
    else
    {
        for(i = 0; i < N*M; ++i)
        {
            bufProc[i] = buff[i];
        }
    }

	fftr1(bufProc,N*M,1); // forward

}	// forwardFFTRun

//
// Input/temp:  bufProc[N*M]
// Output:      bufOut[N]
// Temp:        buff[N*M]
// Input:       N - output size
// Input:       M - overlapped coefficient
//
void backwardFFTRun(float* bufProc, __int16* bufOut, float* buff, const int N, const int M)
{
	int i, j;
	if((NULL == buff) || (NULL == bufProc) || (NULL == bufOut))
	{
		return;
	}

	fftr1(bufProc,N*M,-1); // backward

	// shift
	for(i = 0; i < N; ++i)
	{
		for(j = 0; j < M-1; ++j)
		{
			buff[i+j*N] = buff[i+(j+1)*N];
		}
		buff[i+(M-1)*N] = 0;
	}

	// add
	for(i = 0; i < N*M; ++i)
	{
//		buff[i] += bufProc[i];
		buff[i] = (buff[i] + bufProc[i]) * 0.5f; // ?
	}

	for(i = 0; i < N; ++i)
	{
		bufOut[i] = (__int16)(buff[i] * 32767.0f);
	}

}	// backwardFFTRun
